import router from './router'
import store from './store'
import { Message } from 'element-ui'
// NProgress 进度条
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { asyncRoutes } from '@/router'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist
// 路由全局前置守卫
router.beforeEach(async(to, from, next) => {
  // start progress bar
  // 开始 进度条
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      // next({ path: '/' })
      next('/')
      // next（地址）并没有执行后置守卫
      // next('/') 不会走后置守卫，直接中转到对应页显示
      NProgress.done()
    } else {
      // 判断一个属性就行了，这是学习getters
      const hasGetUserInfo = store.getters.name
      const userId = store.getters.userId
      // 判断是否获取过资料
      if (hasGetUserInfo && userId) {
        // 通过 放行
        next()
      } else {
        try {
          // get user info
          // 获取用户信息
          const { roles } = await store.dispatch('user/getUserInfo')
          // console.log(roles.menus) // 数组 不确定 可能是8个 1个 0个
          // console.log(asyncRoutes) // 数组 8个
          // 获取用户权限信息
          // 根据用户权限添加动态路由
          if (roles?.menus) {
            // 筛选后的路由
            const filterRoutes = asyncRoutes.filter(item => roles.menus.includes(item.path.substring(1)))
            // 把动态路由放到vuex 中
            store.commit('user/setRoutes', filterRoutes)
            // 添加动态路由信息到路由表 动态挂载
            router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
            // router添加动态路由之后 需要转发一下
            next(to.path) // 目的是让路由拥有信息 router的已知缺陷
          } else {
            // 通过 放行
            next()
          }
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/logout')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    // if (whiteList.indexOf(to.path) !== -1) {
    // 没有token
    if (whiteList.includes(to.path)) {
      // in the free login whitelist, go directly
      // 通过 放行
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      // next（地址）并没有执行后置守卫
      NProgress.done()
    }
  }
})
// 路由全局后置守卫(全局后置钩子)
router.afterEach(() => {
  console.log('(============->)')
  // finish progress bar
  // 关闭 进度条
  NProgress.done()
})

// 后置守卫 参数
// router.afterEach((to, from) => {
//   console.log(to, from)
// })
